<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		errorModal,
		ignoreHtml,
		getUrl,
		confirmModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		changeConfigAttr,
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		formShowLoading,
		getFormFields,
		hasEditor,
		getEditorTitle,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				userCacheKey:"hr-kq-tsupplementAttendance-user-cache",
				fromWorkInfo:false
			})  
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		methods:{
			//将时分秒转为时间戳
			  time_to_sec(time) {
			        if (time !== null) {
			            var s = "";
			            var hour = time.split(":")[0];
			            var min = time.split(":")[1];
			            var sec = time.split(":")[2];
			            s = Number(hour * 3600) + Number(min * 60) + Number(sec);
			            return s;
			        }
			    },
			getSubList(date,time){
				let _that = this
				_that.om.request(
					"tsupplementAttendance/getRepairNodeList",
					{
						userId: _that.userId,
						date:date
					}
				).then(res=>{
					let arr = []
					if(!_that.addRepair){
						for(let item of res){
							if(time.indexOf(item.stdtime) != -1){
							let obj = {
								attendanceNodeName:item.nodeSimpleName,
								attendanceRecord: "",
								group: null,
								nodeEndTime: item.endtime,
								nodeStartTime: item.starttime,
								nouse: null,
								reasonId:'',
								reasonName: "",
								remark: "",
								selected: null,
								supplementDate: date,
								supplementTime: time,
								}
								arr.push(obj)
							}
						}
					}else{
						for(let oItem of res){
							if(_that.time_to_sec(oItem.starttime+':00')<=_that.time_to_sec(_that.absentTime+':00') && _that.time_to_sec(_that.absentTime+':00') <= _that.time_to_sec(oItem.endtime+':00') && _that.time_to_sec(_that.absentTime+':00') <= _that.time_to_sec(oItem.stdtime+':00')){
							let obj = {
								attendanceNodeName:oItem.nodeSimpleName,
								attendanceRecord: "",
								group: null,
								nodeEndTime: oItem.endtime,
								nodeStartTime: oItem.starttime,
								nouse: null,
								reasonId:'',
								reasonName: "",
								remark: "",
								selected: null,
								supplementDate: date,
								supplementTime: _that.absentTime,
								}
								if(!arr.length){
									arr.push(obj)
								}
							}
							if(_that.absentTime1){
								if(_that.time_to_sec(oItem.starttime+':00')<=_that.time_to_sec(_that.absentTime1+':00') && _that.time_to_sec(_that.absentTime1+':00') <= _that.time_to_sec(oItem.endtime+':00')){
								let obj = {
									attendanceNodeName:oItem.nodeSimpleName,
									attendanceRecord: "",
									group: null,
									nodeEndTime: oItem.endtime,
									nodeStartTime: oItem.starttime,
									nouse: null,
									reasonId:'',
									reasonName: "",
									remark: "",
									selected: null,
									supplementDate: date,
									supplementTime: _that.absentTime1,
									}
									arr.push(obj)
								}
							}
						}
					}
					_that.subEditorObj["dataInfo"].workList = arr
				})
			},
			getDateList(d){
				let _that = this
				let formdata = _that.$refs.autoform.formdata			
				_that.om.request("tsupplementAttendance/getVerifyObj",{
					userId:d.id,
				}).then(res=>{
					if(res.succeed){
						let value = res.value;
						if (value.tip) {
							confirmModal(_that, "提示信息",value.tip, function() {
								let comboboxList = value.comboboxList;
								if (!comboboxList || comboboxList.length === 0) {
								    _that.$refs.autoform.clearGroup("userInfo")
								    _that.$set(_that.formdata,"userId","")
								    _that.$set(_that.formdata,"userName","")
								    _that.subEditorObj['dataInfo'].workList = []
								} else {
								    //补签时间
									_that.getUserSalaryPosInfo(d.id)
								}
							});
						} else {
						    let comboboxList = value.comboboxList;
						    if (!comboboxList || comboboxList.length === 0) {
								confirmModal(_that, "提示信息",d.username+"没有可补签的日期", function() {
									_that.$refs.autoform.clearGroup("userInfo")
									_that.$set(_that.formdata,"userId","")
									_that.$set(_that.formdata,"userName","")
									_that.subEditorObj['dataInfo'].workList = []
								});
						    } else {
						        //补签时间
								_that.getUserSalaryPosInfo(d.id)
						    }
						}
					}else{
						errorModal(_that,'提示信息',res.msg,()=>{
							_that.$refs.autoform.clearGroup("userInfo")
							_that.$set(_that.formdata,"userId","")
							_that.$set(_that.formdata,"userName","")
							_that.subEditorObj['dataInfo'].workList = []
						})		
					}
				})
			},
			formSubmit(){
				let _that = this
				_that.formdata.newFileFlag = true
				_that.formdata.updateBottomFileFlag= true
				delete _that.formdata.bottomFileUpload
				delete _that.formdata.bottomFileList
				if(Object.prototype.toString.call(_that.$refs.autoform.formdata.bottomFileList) == "[object String]"){
					_that.formdata.bottomFileListStr = _that.$refs.autoform.formdata.bottomFileList|| ''
				}else{
					_that.formdata.bottomFileListStr = JSON.stringify(_that.$refs.autoform.formdata.bottomFileList || []) || ''
				}
					
				if(_that.formdata.userId && _that.subEditorObj["dataInfo"].workList.length){
					_that.om.formSave("tsupplementAttendance/save",_that.formdata,_that)
				}else{
					let title = _that.$refs.autoform.getGroupTitle("dataInfo")
					_that.om.toast("请配置" +"“"+title+"”")
				}
			},
			verifyDataInfo(){
				let _that = this
				if(!_that.$refs.autoform.formdata.userId){
					let title = _that.$refs.autoform.getEditorTitle("userInfo","userId")
					_that.om.toast("请先选择"+title)
					return false
				}else{
					return true
				}
			},
			getWorkParam(){
				let _that = this
				return {
					userId:_that.$refs.autoform.formdata.userId
				}
			},
			getUserSalaryPosInfo(id){
				let _that = this
				_that.om.request(
					"orgInstPosUserOfficial/getUserSalaryPosInfo",
					{
						userId:id
					}
				).then(res=>{
					if(res.succeed){
						_that.$refs.autoform.formdata.salaryPosName = res.value.posName
						_that.$refs.autoform.formdata.salaryInstName = res.value.instName
						_that.$refs.autoform.formdata.parentInstName = res.value.parentInstName
						_that.$refs.autoform.formdata.salarycatId = res.value.salaryCatId
						_that.$refs.autoform.formdata.salaryCatName = res.value.salaryCatName
						_that.$refs.autoform.formdata.parentUserName  =  res.value.parentUserName
						_that.$refs.autoform.formdata.remark = res.value.remark
						_that.$refs.autoform.formdata.instLevelId =  res.value.instCatId
						_that.$refs.autoform.formdata.instLevelName =  res.value.instCatName
					}
				})
			},
			initLoad(options){
				let _that = this
				let ajaxArr = [{
					url:"tsupplementAttendance/getTitleInfo"
				}]
				let fileId = options.fileId
				if(fileId){
					ajaxArr.push({
						url:"tsupplementAttendance/getInfo",
						param:{
							id:fileId
						}
					})
				}
				formModelLoad(ajaxArr,function(res,mainData){
					changeEditor('topinfo','zuserId',{
						defaultName:_that.userName,
						defaultValue:_that.userId
					},null, mainData);
					changeEditor("userInfo","userId",{
						link:"../../public/pageSearch/pageSearch",
						"linkParam":{
							other: JSON.stringify({
							}),
							namefield:urlUtil.findUserAsSameInst().namefield,
							extrafield:urlUtil.findUserAsSameInst().extrafield,
							searchfield:"q",
							initload:true,
							url:urlUtil.findUserAsSameInst().url ,
							cachename:_that.userCacheKey,
							placeholder:"请输入姓名"
						}
					},null,mainData)
					if(_that.subEditorObj["dataInfo"]){
						let att = {
							getWorkParam:"getWorkParam"
						}
						let configData = _that.subConfigData["dataInfo"]
						if(hasEditor("dataInfo","supplementDate",configData)){
							let title = getEditorTitle("dataInfo","supplementDate",configData)
							att.titleTemplate = title+":<%=supplementDate || '未填写'%>"
						}
						if(hasEditor("dataInfo","supplementTime",configData)){
							let title = getEditorTitle("dataInfo","supplementTime",configData)
							att.subtitle2Template = title+":<%=supplementTime || '未填写'%>"
						}
						if(hasEditor("dataInfo","attendanceNodeName",configData)){
							let title = getEditorTitle("dataInfo","attendanceNodeName",configData)
							att.subtitle1Template = title+":<%=attendanceNodeName || '未填写'%>"
						}
						changeEditor('dataInfo','dataStr',att,mainData)
					}
					changeEditor('fileInfo','formUpload','fileUploadKey',"32",mainData)
					_that.$set(_that.formdata,"titleInfo",res[0].value)
					changeConfigAttr("dataInfo","subTitle",res[0].value,mainData)
					if(res[1][0]){
						changeEditor('repairInfo','reasonId',{
							defaultName:res[1][0].dicname,
							defaultValue:res[1][0].id
						},null,mainData)
					}
					
					let tempFileList = []
					let fileUrlList = []
					changeEditor('bottominfo','bottomFileUpload','fileUploadKey',"38",mainData)
					changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
					changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
					
					if(fileId){
						let fieldArr = getFormFields(mainData)
						fieldArr.push("id")
						for(let index in res[1].value){
							if(fieldArr.includes(index)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[1].value[index])
								_that.$set(_that.formdata,index,res[1].value[index])
							}
						}
						if(_that.formdata.bottomFileList){
							let tempFileList = []
							let fileUrlList = _that.formdata.bottomFileList.map(t=>{
								tempFileList.push(t.fileSaveName)
								return t.fileSaveName
							})
							changeEditor("bottominfo","bottomFileUpload","tempFileList", tempFileList,mainData)
							changeEditor("bottominfo","bottomFileUpload","fileUrlList", fileUrlList,mainData)
						}
						
						if( _that.subEditorObj["dataInfo"]){
							let dataList = _that._.cloneDeep(res[1].value.dataList)
							_that.subEditorObj["dataInfo"].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataStr",JSON.stringify(dataList))
							_that.$set(_that.formdata,"dataStr",JSON.stringify(dataList))
						}
					}
					_that.$nextTick(function(){
						if(!_that.$refs.autoform.formdata.userId){
							_that.$refs.autoform.formdata.userId = _that.userId
							_that.$refs.autoform.formdata.userName = _that.userName
							_that.getDateList({id:_that.userId,username:_that.userName})
						}
						if(_that.fromWorkInfo){
							if(_that.absentDate){
								_that.om.request(
									"tsupplementAttendance/getDateList",
									{
										userId:_that.$refs.autoform.formdata.userId
									}
								).then(res=>{
									for(let item of res){
										if(item.value == _that.absentDate){
											_that.getSubList(_that.absentDate ,_that.absentTime)
										}
									}
								})
							}
						}
					})
					
				},options)
			}
		},
		onUnload(){
					//#ifdef APP-PLUS
					let _that = this;
					if (_that.$refs.autoform) {
						for (var fieldId in _that.subEditorObj) {
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					}
					//#endif
				},
		onLoad(options) {
			let _that = this
			if(options.absentDate){
				_that.fromWorkInfo = true
				_that.absentDate = options.absentDate
				_that.absentTime = options.absentTime
				if(options.absentTime1){
					_that.absentTime1 = options.absentTime1
				}
				if(options.addRepair){
					_that.addRepair = true
				}
			}
			_that.initLoad(options)
		},
		onShow() {
			let _that = this
			if(_that.$refs.autoform){
				for(let fileId in _that.subEditorObj){
					let editor = _that.subEditorObj[fileId]
					uni.getStorage({
						key:getWorkCacheKey(fileId),
						success:(res)=>{
							editor.workList = res.data
							uni.removeStorage({
								key:getWorkCacheKey(fileId)
							})
						}
					})
				}
				uni.getStorage({
					key: _that.userCacheKey,
					success: function(res) {
						if(res.data){
							let d = res.data
							var formdata  = _that.$refs.autoform.formdata
							formdata.userId = d.id
							formdata.userName = d.username
							_that.getDateList(d)
							uni.removeStorage({
								key: _that.userCacheKey
							});
						}
					}
				});
			}
		}
	}
</script>
<style></style>                                                                                                                                                                                                                                                                                                                  
